extends Node
class_name OrcSkill

@export var orc: Orc
@onready var body: Node2D = %body
@onready var attack_area: Area2D = %AttackArea
@export var enemy_hit_box_component: EnemyHitBoxComponent
@export var ghost_node: PackedScene
@onready var orc_state: OrcState = %OrcState

## 初始速度
var init_speed: float
## 初始攻击前摇
var init_attack_delay: float
var init_size: float
var timer: Timer

func _ready() -> void:
	await owner.ready
	init_speed = orc.orc_stats.get_float("speed")
	init_attack_delay = orc.orc_stats.get_float("attack_delay")
	init_size = enemy_hit_box_component.length
	
## 不断狂暴
func rage():
	_update_rage_stats()
	# 添加狂暴特效
	timer = Timer.new()
	timer.one_shot = false
	timer.wait_time = 0.5
	timer.timeout.connect(on_time_out)
	self.add_child(timer)
	timer.start()
	## 五秒后解除狂暴
	await get_tree().create_timer(5).timeout
	_exit_rage_state()

func _exit_rage_state() -> void:
	orc.orc_stats.set_bool("is_rage", false)
	orc.orc_stats.set_float("speed", init_speed)
	orc.orc_stats.set_float("attack_delay", init_attack_delay)
	orc.orc_stats.set_float("defense", 0.0)
	body.modulate = Color(1, 1, 1)
	enemy_hit_box_component.length = init_size
	orc.sprite.speed_scale = 1
	attack_area.scale = Vector2(1, 1)
	if timer != null:
		timer.queue_free()
	
func create_ghost() -> void:
	var ghost = ghost_node.instantiate()
	ghost.set_property(owner.global_position, body , owner.scale)
	add_child(ghost)

func _update_rage_stats() -> void:
	Utils.show_string_label_c("狂暴", orc, Color.RED)
	body.modulate = Color(1.5, 0.5, 0.5)
	orc.orc_stats.set_float("speed", orc.orc_stats.get_float("speed") * 2)
	orc.orc_stats.set_float("attack_delay", 0.1)
	enemy_hit_box_component.length *= 1.2
	orc.sprite.speed_scale *= 2
	orc.orc_stats.set_bool("is_rage", true)
	orc.orc_stats.set_float("defense", 1)
	attack_area.scale = Vector2(0.8, 0.8)

func on_time_out():
	orc_state.rage_enter_timer = 0
	create_ghost()
